package com.mymarkdown.app.controller;

import cn.hutool.core.io.IoUtil;
import com.mymarkdown.app.interfaces.ModifyWindow;
import com.mymarkdown.app.interfaces.UserInfoService;
import com.mymarkdown.app.service.MdService;
import com.mymarkdown.app.service.SaveMdBodyService;
import com.mymarkdown.app.websocket.message.MessagePojo;
import com.mymarkdown.app.common.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.BlockingQueue;

/**
 * @author zenglun
 * @date 2021/12/6 8:17 上午
 * @description: TODO
 */
@Slf4j
@RequestMapping("/md")
@RestController
public class MdController {

    @Autowired
    private SaveMdBodyService saveMdBodyService;

    @Autowired
    private MdService mdService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private ModifyWindow modifyWindow;

    @GetMapping("/getOpenMdBody")
    public ResponseResult getOpenMdBody() {
        FileInputStream fileInputStream = null;
        try {
            BlockingQueue<File> operationFile = userInfoService.getOperationFile();
            File file = operationFile.peek();
            if (Objects.isNull(file)) {
                file = operationFile.take();
            }
            //开始读取相关文件数据
            fileInputStream = new FileInputStream(file);
            String read = IoUtil.read(fileInputStream, StandardCharsets.UTF_8);
            //返回数据内容
            return ResponseResult.ok(read);
        } catch (InterruptedException | FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            Optional.ofNullable(fileInputStream).ifPresent(e -> {
                try {
                    e.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            });
        }
        return ResponseResult.error();
    }

    @PostMapping("/uploadMd")
    public ResponseResult uploadMd(@RequestBody MessagePojo messagePojo) {
        if (Objects.isNull(messagePojo)) {
            return ResponseResult.error();
        }
        try {
            saveMdBodyService.saveMdBoy(messagePojo.getBody(), userInfoService.getSession(), true);
            userInfoService.setFileSaveState(true);
            modifyWindow.changeTitle();
        } catch (Exception e) {
            log.error("[MdController]---[uploadMd],上传Md内容失败,异常信息为:{}", e);
            return ResponseResult.error();
        }
        return ResponseResult.ok("");
    }

    @PostMapping("/autoUploadMd")
    public ResponseResult autoSaveMd(@RequestBody MessagePojo messagePojo) {
        if (Objects.isNull(messagePojo)) {
            return ResponseResult.error();
        }
        BlockingQueue<File> operationFile = userInfoService.getOperationFile();
        File peek = operationFile.peek();

        if (Objects.isNull(peek) || !peek.exists()) {
            return ResponseResult.error();
        }
        try {
            saveMdBodyService.saveMdBoy(messagePojo.getBody(), userInfoService.getSession(), false);
            userInfoService.setFileSaveState(true);
            modifyWindow.changeTitle();
        } catch (Exception e) {
            log.error("[MdController]---[uploadMd],上传Md内容失败,异常信息为:{}", e);
            return ResponseResult.error();
        }
        return ResponseResult.ok("");
    }


    @PostMapping("/uploadMdToHTML")
    public ResponseResult uploadMdToHTML(@RequestBody MessagePojo messagePojo) {
        if (Objects.isNull(messagePojo)) {
            return ResponseResult.error();
        }
        try {
            return mdService.saveMdHTMLBody(messagePojo.getBody());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("[MdController]---[uploadMdToHTML],上传Md HTML内容失败,异常信息为:{}", e);
        }
        return ResponseResult.error();
    }

}
